import React, { Component } from 'react'
import { connect } from 'dva'
import { message, Tabs } from 'antd'
import BaseLayout from "@/components/Layout/BaseLayout";
import ExamList from "@/components/ExamList/ExamList";
import ExamInfoAside from "@/components/ExamList/ExamInfoAside";
import ExamPaper from "@/components/ExamList/ExamPaper";
import StudentInfoAside from '@/components/ExamList/StudentInfoAside'
import AnswerSheet from '@/components/AnswerSheet/AnswerSheet'
import StuInfo from '@/components/UserInfo/StuInfo'
import { history } from 'umi'

import questionList from '@/utils/test/questionList'
import dataSource from '@/utils/test/examList'
import questionNumberList from '@/utils/test/questionNumberList'
import { getExamListByStuId, getScoreInfoByStuIdAndExamId } from '@/services/exam'
import { getCookie } from '@/utils/cookie/cookie';

const { TabPane } = Tabs
const mapStateToProps = (state) => {
    const { token } = state['token']
    const { examListTab } = state['student']
    const { ws } = state["websocket"]
    return { token, examListTab, ws }
}
const mapDispatchToProps = (dispatch) => {
    return {
        changeToExamList() {
            dispatch({
                type: `student/changeState`,
                result: { data: "examList" },
                field: "examListTab",
            });
        },
        changeToExamPaper() {
            dispatch({
                type: `student/changeState`,
                result: { data: "examPaper" },
                field: "examListTab",
            });
        },
        changeToExamScore() {
            dispatch({
                type: `student/changeState`,
                result: { data: "examScore" },
                field: "examListTab",
            });
        },
        changeExamListTab(examListTab) {
            dispatch({
                type: `student/changeState`,
                result: { data: examListTab },
                field: "examListTab",
            });
        },
    };
};

let timer = null
let wsConnetTimer = null
class Index extends Component {

    constructor(props) {
        super(props)
        this.state = {
            examList: [],
            examListIndex: 0,
            stuAnswerList: []
        }
    }

    componentDidMount() {
        (async () => {
            message.loading({
                key: 'tip',
                content: '加载中'
            })
            const result = await getExamListByStuId({ stu_id: getCookie("userId") })
            if (result.status === 0) {
                this.setState({
                    examList: result.data.map((data) => {
                        return {
                            key: data.exam_id,
                            title: data.exam_title,
                            status: data.exam_status,
                            startTime: data.start_time,
                            endTime: data.end_time,
                            class: data.class_id.split(','),
                            maxScore: data.max_score,
                            passScore: data.pass_score,
                            examPaperId: data.exam_paper_id
                        }
                    })
                })
                message.success({
                    key: 'tip',
                    content: '加载完毕',
                    duration: 1
                })
            } else {
                message.error({
                    key: 'tip',
                    content: '加载失败',
                    duration: 1
                })
            }
        })();

        if (getCookie("identity") !== "student") {
            message.error("error");
            history.push('/Login')
        }
        timer = setInterval(() => {
            if (getCookie("identity") !== "student") {
                message.error("error");
                history.push('/Login')
            }
        }, 500);
        wsConnetTimer = setInterval(() => {
            console.log("connect...")
            const { ws } = this.props
            if (ws instanceof WebSocket) {
                console.log("setOnMessage")
                ws.onmessage = (message) => {
                    const messageData = message.data
                    const { examListStatus } = JSON.parse(messageData)
                    const nextExamList = JSON.parse(JSON.stringify({ data: this.state.examList })).data
                    console.log("update:", JSON.parse(messageData))
                    if (examListStatus instanceof Array) {
                        if (nextExamList instanceof Array) {
                            examListStatus.forEach((data1) => {
                                const index = nextExamList.findIndex((data2) => {
                                    return data1.exam_id === data2.key
                                })
                                if (index > -1) {
                                    if (data1.exam_status) {
                                        nextExamList[index].status = data1.exam_status
                                    }
                                    if (data1.deleted === 1) {
                                        nextExamList.splice(index, 1)
                                    }
                                }
                            })
                        }
                    }
                    if (nextExamList !== this.state.examList) {
                        this.setState({
                            examList: nextExamList
                        })
                    }
                }
                clearInterval(wsConnetTimer)
                wsConnetTimer = null
            }
        }, 500)
    }

    componentWillUnmount() {
        if (timer) {
            clearInterval(timer)
        }
        const { ws } = this.props
        if (ws instanceof WebSocket) {
            ws.onmessage = () => { }
        }
        if (wsConnetTimer) {
            clearInterval(wsConnetTimer)
            wsConnetTimer = null
        }
    }

    render() {
        const tabPaneMap = {};
        const { examList, examListIndex } = this.state
        tabPaneMap.examList = <TabPane tab="考试列表" key="考试列表">
            <ExamList
                dataSource={this.state.examList?.map?.((data, index) => {
                    return {
                        ...data,
                        onHoverList: [
                            {
                                text: '开始考试',
                                onClick: async () => {
                                    const result = await getScoreInfoByStuIdAndExamId({
                                        stu_id: getCookie("userId"),
                                        exam_id: data.key
                                    })
                                    if (result.status === 0 && result.data) {
                                        message.warn("你已完成了此次考试，待考试结束时间之后可查看成绩")
                                    } else {
                                        this.setState({
                                            examListIndex: index
                                        }, () => {
                                            this.props.changeToExamPaper()
                                        })
                                    }
                                },
                                show: data.status === "ongoing"
                            },
                            {
                                text: '查看成绩',
                                onClick: () => {
                                    this.setState({
                                        examListIndex: index
                                    }, () => {
                                        this.props.changeToExamScore()
                                    })
                                },
                                show: data.status === "over"
                            }
                        ]
                    }
                })}
            />
        </TabPane>
        tabPaneMap.examPaper = <TabPane tab="考试列表" key="考试列表">
            <ExamInfoAside
                onBack={this.props.changeToExamList}
                info={examList[examListIndex]}
                canEdit={false}>
                <ExamPaper
                    type="doPaper"
                    info={examList[examListIndex]}
                    examPaperId={examList[examListIndex]?.examPaperId}
                    showTrueAnswer={false}
                    showSubmitBtn={true}
                    getStuAnswerList={(stuAnswerList) => {
                        this.setState({
                            stuAnswerList
                        })
                    }} />
                <AnswerSheet dataSource={this.state.stuAnswerList} />
            </ExamInfoAside>
        </TabPane>
        tabPaneMap.examScore = <TabPane tab="考试列表" key="考试列表">
            <StudentInfoAside
                onBack={this.props.changeToExamList}
                info={examList[examListIndex]}
                canEdit={false}>
                <ExamPaper
                    type={"checkPaper"}
                    info={examList[examListIndex]}
                    examPaperId={examList[examListIndex]?.examPaperId}
                    showTrueAnswer={true}
                    showStudentAnswer={true}
                />
            </StudentInfoAside>
        </TabPane>
        tabPaneMap.stuInfo = <TabPane tab='个人信息' key='个人信息'>
            <StuInfo></StuInfo>
        </TabPane>
        const tabsPane = []
        tabsPane.push(tabPaneMap[this.props.examListTab] ? tabPaneMap[this.props.examListTab] : tabPaneMap['examList'])
        tabsPane.push(tabPaneMap.stuInfo)
        return <BaseLayout
            title='在线考试·学生'
            tabsPane={tabsPane}>
        </BaseLayout>
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index)